package com.power.leopard.remote.common.codec.java;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;

public class CompactObjectOutputStream extends ObjectOutputStream {

	public CompactObjectOutputStream(OutputStream out) throws IOException {
		super(out);
	}

	static final int TYPE_FAT_DESCRIPTOR = 0;
	static final int TYPE_THIN_DESCRIPTOR = 1;

	@Override
	protected void writeStreamHeader() throws IOException {
		writeByte(STREAM_VERSION);
	}

	@Override
	protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {
		Class<?> clazz = desc.forClass();
		if (clazz.isPrimitive() || clazz.isArray()) {
			write(TYPE_FAT_DESCRIPTOR);
			super.writeClassDescriptor(desc);
		} else {
			write(TYPE_THIN_DESCRIPTOR);
			writeUTF(desc.getName());
		}
	}

	public static void main(String[] args) throws FileNotFoundException, IOException {
		Demo demo = new Demo();
		demo.setA(1);
		demo.setB("helloworld");
		demo.setC(2.3);
		demo.setD(5);
		ObjectOutputStream oos = new CompactObjectOutputStream(new FileOutputStream("/data/applogs/a"));
		oos.writeObject(demo);
		oos.close();

		oos = new ObjectOutputStream(new FileOutputStream("/data/applogs/b"));
		oos.writeObject(demo);
		oos.close();

		byte[] bytes = new byte[1024];
		FileInputStream fileInputStream = new FileInputStream("/data/applogs/a");
		fileInputStream.read(bytes);
		String convertByte2Hex = convertByte2Hex(bytes);
		System.out.println(new String(bytes));
		fileInputStream.close();

		fileInputStream = new FileInputStream("/data/applogs/b");
		fileInputStream.read(bytes);
		convertByte2Hex = convertByte2Hex(bytes);
		System.out.println(new String(bytes));
		fileInputStream.close();

		String a = "com.power.leopard.remote.common.codec.java.Demo";
		byte[] bytes2 = a.getBytes("UTF-8");
		// System.out.println(bytes2);
	}

	private static String convertByte2Hex(byte[] encrpt) {
		StringBuilder sb = new StringBuilder();
		for (byte b : encrpt) {
			int ab = b & 0xFF;
			String hex = Integer.toHexString(ab);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex);
		}
		return sb.toString();
	}
}
